package com.px.lovepath.datebase;

import java.util.LinkedList;

import android.os.Looper;

import com.px.lovepath.LoveAppListener;
import com.px.lovepath.LovePath;
import com.px.lovepath.ui.general.LoveActivity;


public class DatabaseManager implements LoveAppListener {

	private static DatabaseManager mSingleton = null;
	private final LovePath mApp;
	private LinkedList<ManagedDatabase> mDbList = new LinkedList<ManagedDatabase>();
	
	// ### 构造函数 ###
	private DatabaseManager(LovePath app) {
		mApp = app;
		
		mApp.addAppListener(this);
	}

	// ### 方法 ###
	public synchronized ManagedDatabase addDatabase(ManagedDatabaseInfo dbInfo) {
		assert dbInfo != null;
		
		ManagedDatabase db = findDatabase(dbInfo.mDbUri);
		if (db == null) {
			db = new ManagedDatabase(dbInfo);
			mDbList.add(db);
		}
		
		return db;
	}
	public static DatabaseManager get() {
		assert mSingleton != null;
		return mSingleton;
	}
	public static void startup(LovePath app) {
		assert Thread.currentThread() == Looper.getMainLooper().getThread();
		assert mSingleton == null;
		mSingleton = new DatabaseManager(app);
	}

	// ### 实现接口 ###
	@Override
	public void onActivityPause(LoveActivity activity) {
		
	}
	@Override
	public void onActivityResume(LoveActivity activity) {
		for (ManagedDatabase db : mDbList) {
			db.close();
		}
	}
	
	// ### 实现函数 ###
	private ManagedDatabase findDatabase(String dbUri) {
		assert dbUri != null;
		
		for (ManagedDatabase db : mDbList) {
			if (db.getDatabaseUri().equals(dbUri)) {
				return db;
			}
		}
		
		return null;
	}

}
